package com.adf.system.license;

import com.adf.config.Config;
import com.adf.system.assistant.ADFAssistant;
import de.schlichtherle.license.*;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.prefs.Preferences;

/**
 * VerifyLicense
 * @author melina
 */
public class VerifyLicense {
	//common param
	private static String PUBLICALIAS = "publiccert";
	private static String STOREPWD = "twsoft2018";
	private static String SUBJECT = "adp";
	private static String licPath = "adp.lic";
	private static String pubPath = "publicCerts.store";
	
	public void setParam(String propertiesPath) {
		// 获取参数

		String spropFile = ADFAssistant.getInstance().getRealFilePath(Config.configpath,propertiesPath);
		spropFile = "/" + spropFile;
		spropFile = spropFile.replace("%20", " ");
		 
		Properties prop = new Properties();
		
		InputStream in = null;
        try
        {
        	in = getClass().getResourceAsStream(spropFile);
        	if (in!=null)
        	{
        		try {
        			prop.load(in);
        		} catch (IOException e) {
        			e.printStackTrace();
        		}
        		PUBLICALIAS = prop.getProperty("PUBLICALIAS");
        		STOREPWD = prop.getProperty("STOREPWD");
        		SUBJECT = prop.getProperty("SUBJECT");
        		licPath = prop.getProperty("licPath");
        		pubPath = prop.getProperty("pubPath");
        		
        	}
        }catch(Exception e)
        {
			System.out.println("获取参数失败!");
        	//e.printStackTrace();
			System.out.println(Encrypt("invalid license config!","1234567890654321"));
        }finally
        {
            try
            {
                if(in!=null) in.close();
            }catch(IOException e)
            {
                //e.printStackTrace();
            }
        }
	}

	public boolean verify() {		
		/************** 证书使用者端执行 ******************/
        LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager(initLicenseParams());
		// 安装证书
		try {
			String slicPath = ADFAssistant.getInstance().getRealFilePath(Config.configpath,licPath);
			
			//slicPath = this.getClass().getResource("/").getPath() + slicPath;
			//System.out.println(slicPath);
			//slicPath = slicPath.replace("%20", " ");
			//System.out.println(slicPath);
			
	        // 20200722 修改classes路径获取方法
	        String rootPath = "";
	        if (this.getClass().getResource("").getPath()!=null){
	        	File fclasses = new File(this.getClass().getResource("").getPath());
	        	rootPath = fclasses.getAbsolutePath();
	        }else{
	        	rootPath = this.getClass().getClassLoader().getResource("/").getPath();
	        }
	        rootPath = rootPath.split("com")[0];
	        rootPath = rootPath.replace("%20", " ");
	        
	        slicPath= rootPath + slicPath;


			System.out.println(slicPath);
	        
			licenseManager.install(new File(slicPath));
			//System.out.println("客户端安装证书成功!");
		} catch (Exception e) {
			//e.printStackTrace();
			//System.out.println("客户端证书安装失败!");
			System.out.println(Encrypt("wrong license path!","1234567890654321"));
			return false;
		}
		// 验证证书
		try {
			licenseManager.verify();
			//System.out.println("客户端验证证书成功!");
		} catch (Exception e) {
			e.printStackTrace();
			//System.out.println("客户端证书验证失效!");
			System.out.println(Encrypt("invalid license!","1234567890654321"));
			return false;
		}
		return true;
	}

	// 返回验证证书需要的参数
	private static LicenseParam initLicenseParams() {
		Preferences preference = Preferences
				.userNodeForPackage(VerifyLicense.class);
		CipherParam cipherParam = new DefaultCipherParam(STOREPWD);

		KeyStoreParam privateStoreParam = new DefaultKeyStoreParam(
				VerifyLicense.class, pubPath, PUBLICALIAS, STOREPWD, null);
		LicenseParam licenseParams = new DefaultLicenseParam(SUBJECT,
				preference, privateStoreParam, cipherParam);
		return licenseParams;
	}

	/**
     * 使用参数中的密钥加密
     * @param 明文
     * @param 密钥
     * @return 密文
     */
    private static String Encrypt(String sSrc, String sKey) {
        try{
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

            return new Base64().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
        }catch(Exception e){
            //e.printStackTrace();
        	System.out.println(e.getMessage());
            return "";
        }
    }
    
}